#include "geometry.h"
#include <cstring>

namespace tls{
  void* create_mesh(std::FILE* ply){
    int n_verts,n_faces;
    vec4* verts;
    mesh::tuple* faces;

    char buf[128];

    while(std::fgets(buf,128,ply)){
      if(std::strncmp(buf,"element",7)==0){
	char type[32],dummy[32];
	int n;
	sscanf(buf,"%s%s%d",dummy,type,&n);
	if(std::strncmp(type,"vertex",6)==0)
	  n_verts=n;
	else if(std::strncmp(type,"face",4)==0)
	  n_faces=n;
      }
      else if(std::strncmp(buf,"end_header",10)==0) break;
    }

    verts=new vec4[n_verts];
    faces=new mesh::tuple[n_faces];

    //read vertex
    for(int i=0;i<n_verts;++i){
      std::fgets(buf,128,ply);
      std::sscanf(buf,"%lf%lf%lf",&verts[i].x,&verts[i].y,&verts[i].z);
      verts[i].w=1;
    }
    //read triangle
    for(int i=0;i<n_faces;++i){
      std::fgets(buf,128,ply);
      int t;
      std::sscanf(buf,"%d%d%d%d",&t,&faces[i].a,&faces[i].b,&faces[i].c);
    }

    mesh* res=new mesh;
    res->n_verts=n_verts;
    res->n_faces=n_faces;
    res->verts=verts;
    res->faces=faces;
    return res;
  }

}//namespace tls

